home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part2 / 13715 < prev    next >
Encoding:
Text File  |  1996-08-05  |  1.7 KB  |  56 lines

  1. Newsgroups: comp.lang.c
  2. Path: news.inap.net!news1!ind-000-236-45
  3. From: dlmiller@iquest.net (Doug Miller)
  4. Subject: Re: reversing a string
  5. X-Nntp-Posting-Host: ind-000-236-45.iquest.net
  6. Message-ID: <DpLtt5.Lqu@iquest.net>
  7. Sender: news@iquest.net (News Admin)
  8. Organization: IQuest Network Services
  9. X-Newsreader: News Xpress Version 1.0 Beta #2.1
  10. References: <4k6cjl$j8f@central.server.swt.edu> <4k6jks$fh9@solutions.solon.com>
  11. Date: Tue, 9 Apr 1996 17:00:42 GMT
  12.  
  13. seebs@solutions.solon.com (Peter Seebach) wrote:
  14. >In article <4k6cjl$j8f@central.server.swt.edu>,
  15. >Leland Newsom <ln16674@nyssa.swt.edu> wrote:
  16. >>I have a challenge from a friend of mine.  He wanted me to reverse a string
  17. >>with recursion without using any additional variables or loops.  I got mine
  18. >>to work by using exclusive or, but I needed an additional variable.  Can
  19. >>someone help with this problem without using the additional variable?
  20. >
  21. >It's trivial with something like
  22. >    void rev (char *s) {
  23. >        if (*s) {
  24. >            rev(s + 1);
  25. >            putchar(*s);
  26. >        }
  27. >    }
  28. >but this is not, strictly speaking, fair, as you're using external state
  29. >anyway.
  30. >
  31. >I can't see a way to reverse in place without a temporary of some sort,
  32. >or a loop of some sort, or something which is fundementally equivalent
  33. >to one of those.  There may be one, but I don't know it.
  34. >
  35. >-s
  36.  
  37. How about this:
  38.  
  39. void swap (char *s) {
  40.     if (strlen(s) > 1) {
  41.         if (*s != *(s + strlen(s) - 1)) {    /* fails without this if first & last chars same*/
  42.             *s ^= *(s + strlen(s) - 1);
  43.             *(s + strlen(s) - 1) ^= *s;
  44.             *s ^= *(s + strlen(s) - 1);
  45.         }
  46.         swap (s + 1);
  47.     }
  48. }
  49.  
  50. void rev (char *s) {
  51.     if (strlen(s) > 1) {
  52.         swap (s);
  53.         rev (s + 1);
  54.     }
  55. }
  56.